package com.hy.study.practice.stack;

import java.util.Scanner;

/**
 * 使用数组模拟栈
 */
public class StackArrayDemo {
    public static void main(String[] args) {
        StackArray stack = new StackArray(4);
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        String key = "";
        while (loop) {
            System.out.println("--------please input :");
            System.out.println("show");
            System.out.println("push");
            System.out.println("pop");
            System.out.println("exit");
            key = scanner.next();
            switch (key) {
                case "show":
                    stack.show();
                    break;

                case "push":
                    System.out.println("please input number:");
                    int value = scanner.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try {
                        System.out.println("弹出元素:" + stack.pop());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    loop = false;
                    scanner.close();
                    break;
                default:
                    break;
            }
        }
        System.out.println("---- exit -----");

    }
}

class StackArray {

    private int maxSize = 16;
    private int top = -1;
    private int[] stack;

    public StackArray(int maxSize) {
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }

    /**
     * 判断时候栈是否满
     *
     * @return
     */
    public boolean isFull() {
        return top == maxSize - 1;
    }

    /**
     * 判断栈是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return top == -1;
    }


    /**
     * 添加数据
     */
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈已满,无法压入数据");
            return;
        }
        top++;
        stack[top] = value;
    }

    /**
     * 栈弹出
     *
     * @return
     */
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空,无法弹出");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * 打印 栈中所有的元素  从栈顶开始打印
     */
    public void show() {
        if (isEmpty()) {
            System.out.println("栈为空");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
}